package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.user.UserTypeEnum;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import com.hunttown.mes.rpc.domain.query.AnalysisManageDTOQuery;
import com.hunttown.mes.rpc.domain.query.IotEnterpriseManageDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportManageDepRelDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportManageRoleRelDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 管理员
 * @author: wangjunfu
 * @date: 2018-10-26 15:14:15
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/manage")
public class ManageController {

    private final static Logger logger = LoggerFactory.getLogger(ManageController.class);

    private final AnalysisManageManageService manageService;
    private final AnalysisManageRightRoleManageService roleService;
    private final AnalysisManageRightRoleAdminRelManageService rightRoleAdminRelService;
    private final IotEnterpriseManageRelService enterpriseRelService;
    private final TransportOperateLogManageService logService;
    private final TransportUserManageService userService;
    private final TransportDepartmentManageService departmentService;
    private final TransportRolesManageService manageRoleService;
    private final TransportStaffGradeManageService gradeService;
    private final TransportManageRoleRelManageService roleManageService;
    private final TransportManageDepRelManageService depManageService;
    private final ModelService modelService;

    @Autowired
    public ManageController(AnalysisManageManageService manageService, AnalysisManageRightRoleManageService roleService, AnalysisManageRightRoleAdminRelManageService rightRoleAdminRelService, IotEnterpriseManageRelService enterpriseRelService, TransportOperateLogManageService logService, TransportUserManageService userService, TransportDepartmentManageService departmentService, TransportRolesManageService manageRoleService, TransportStaffGradeManageService gradeService, TransportManageRoleRelManageService roleManageService, TransportManageDepRelManageService depManageService, ModelService modelService) {
        this.manageService = manageService;
        this.roleService = roleService;
        this.rightRoleAdminRelService = rightRoleAdminRelService;
        this.enterpriseRelService = enterpriseRelService;
        this.logService = logService;
        this.userService = userService;
        this.departmentService = departmentService;
        this.manageRoleService = manageRoleService;
        this.gradeService = gradeService;
        this.roleManageService = roleManageService;
        this.depManageService = depManageService;
        this.modelService = modelService;
    }

    //region 首页
    @RequestMapping(value = "/index_role", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, AnalysisManageDTOQuery dtoQuery) {

        //area_id 是一个公用字段，在全渠道客服系统中存储的是：台区ID；其它情况下根据业务需要存储。
        //is_group 普通员工为0，不在管理帐号中显示；管理员工为1；
        if (dtoQuery.getWorkOfiice() == null || dtoQuery.getWorkOfiice() == 0) {
            dtoQuery.setIsGroup(1);
        } else {
            dtoQuery.setIsGroup(null);
        }

        //在职
        if (dtoQuery.getOnJob() == null) {
            dtoQuery.setOnJob(0);
        }

        //离职
        if (dtoQuery.getOffJob() == null) {
            dtoQuery.setOffJob(0);
        }

        // 当前用户
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        model.addAttribute("isSuper", curr_obj.getIsSuper());

        // 数据列表
        if (curr_obj.getIsSuper() == 0) {
            dtoQuery.setIsSuper(0); //普通用户不显示管理帐号
        }

        //默认不显示离职
        dtoQuery.setStopFlag(0);

        if (dtoQuery.getOffJob() == 1) {
            dtoQuery.setStopFlag(null);
        }

        Page<AnalysisManageDTO> dataPage = manageService.getForPage(dtoQuery);

        // 获取权限信息
        dataPage = manageService.getPageRoleName(dataPage);

        // 实时更新列表信息
        for (AnalysisManageDTO item : dataPage.getItems()) {

            //region 部门
            TransportManageDepRelDTOQuery depQuery = new TransportManageDepRelDTOQuery();
            depQuery.setTableId(13);
            depQuery.setRecordId(item.getId());
            Page<TransportManageDepRelDTO> depPage = depManageService.getForPage(depQuery);

            List<String> depList = new ArrayList<>();
            for (TransportManageDepRelDTO ci : depPage.getItems()) {
                String dname = modelService.getDepName(ci.getDepId());
                if (ci.getDutyId() == 1) {
                    dname += " | 主管";
                }
                depList.add(dname);
            }

            if (depList.size() > 0) {
                item.setDepName(String.join("，", depList));
            }
            //endregion

            //region 角色
            TransportManageRoleRelDTOQuery roleQuery = new TransportManageRoleRelDTOQuery();
            roleQuery.setTableId(13);
            roleQuery.setRecordId(item.getId());
            Page<TransportManageRoleRelDTO> rolePage = roleManageService.getForPage(roleQuery);

            List<String> roleList = new ArrayList<>();
            for (TransportManageRoleRelDTO ci : rolePage.getItems()) {
                String rname = modelService.getRoleName(ci.getRoleId());
                roleList.add(rname);
            }

            if (roleList.size() > 0) {
                item.setRoleName(String.join("，", roleList));
            }
            //endregion

        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "basic/manage/index_role";
    }

    // 首页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Integer id, Integer parentId, Model model) {
        model.addAttribute("adminId", id);
        return "basic/manage/index";
    }

    // 左树
    @RequestMapping(value = "/left_tree", method = RequestMethod.POST)
    public String leftTree(Model model, Integer adminId) {
        if (adminId == null || adminId < 0) {
            adminId = 0;
        }
        AnalysisManageDTO admin_obj = manageService.getFromCacheId(adminId);
        List<String> roleList = roleService.createCateTree(1, adminId, (admin_obj == null ? 0 : admin_obj.getIsSuper()));
        model.addAttribute("roleList", roleList);

        return "basic/manage/left_tree";
    }
    //endregion

    //region 编辑
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(HttpServletRequest request, Model model, Integer id) {
        id = id == null ? 0 : id;

        AnalysisManageDTO obj = new AnalysisManageDTO();
        obj.setId(id);

        if (id > 0) {
            obj = manageService.getById(id);
            obj.setPwd("");
        }

        model.addAttribute("adminObj", obj);

        // 当前用户
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        model.addAttribute("currObj", curr_obj);

        // 获取部门
        // model.addAttribute("depList", departmentService.getForList());

        // 获取职级
        model.addAttribute("gradeList", gradeService.getGradeList());

        // 台区信息（管辖区域）

        // 获取角色
        List<TransportRolesDTO> manageRoleList = manageRoleService.getForList();

        if (id > 0) {
            //region 1.选中了哪个角色
            TransportManageRoleRelDTOQuery roleRelQuery = new TransportManageRoleRelDTOQuery();
            roleRelQuery.setTableId(13);
            roleRelQuery.setRecordId(id);
            roleRelQuery.setPageSize(1000);
            Page<TransportManageRoleRelDTO> roleRelPage = roleManageService.getForPage(roleRelQuery);
            List<Integer> selectIds = new ArrayList<>();
            for (TransportManageRoleRelDTO item : roleRelPage.getItems()) {
                if (!selectIds.contains(item.getRoleId())) {
                    selectIds.add(item.getRoleId());
                }
            }

            for (TransportRolesDTO item : manageRoleList) {
                if (selectIds.contains(item.getId())) {
                    item.setIsSelect(1);
                }
            }
            //endregion

            //region 2.选中了哪个部门
            TransportManageDepRelDTOQuery depRelQuery = new TransportManageDepRelDTOQuery();
            depRelQuery.setTableId(13);
            depRelQuery.setRecordId(id);
            depRelQuery.setPageSize(1000);
            Page<TransportManageDepRelDTO> depRelPage = depManageService.getForPage(depRelQuery);

            for (TransportManageDepRelDTO item : depRelPage.getItems()) {
                item.setDepName(departmentService.getDepName(item.getDepId()));
                item.setDutyName(item.getDutyId() == 1 ? "主管" : "成员");
            }

            model.addAttribute("depRelList", depRelPage.getItems());
            //endregion
        }

        model.addAttribute("manageRoleList", manageRoleList);

        return "basic/manage/edit";
    }

    // 保存
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, AnalysisManageDTO objDTO) {

        // 结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        try {
            String roleids = objDTO.getRoleIds();

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            //创始者的权限只能由创始者本人修改
            if (objDTO.getAdminName().equals("wangjunfu") && !curr_obj.getAdminName().equals("wangjunfu")) {
                map = OperateCode.CompositionResult(map, -10, "对不起，您没有权限修改此用户信息！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            //判断手机号是否合法
            if (!RegexpUtils.checkIsMobile(objDTO.getMobile())) {
                map = OperateCode.CompositionResult(map, -10, "请输入正确的手机号！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            // 生成密码
            if (StringUtils.isNotBlank(objDTO.getPwd())) {
                // 生成SHA1密码
                String password_sha = SHA1Utils.shaEncode(objDTO.getAdminName() + objDTO.getPwd());
                objDTO.setPwd(password_sha);
            }

            if (objDTO.getIsCharge() == null) {
                objDTO.setIsCharge(0);
            }
            if (objDTO.getIsSuper() == null) {
                objDTO.setIsSuper(0);
            }
            if (objDTO.getCustomizeMenu() == null) {
                objDTO.setCustomizeMenu(0);
            }
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }
            if (objDTO.getAreaId() == null) {
                objDTO.setAreaId(0);
            }
            if (objDTO.getAgentId() == null) {
                objDTO.setAgentId(0);
            }

            // 空格检查
            objDTO.setAdminName(objDTO.getAdminName().trim());
            objDTO.setNickName(objDTO.getNickName().trim());
            objDTO.setEmail(objDTO.getEmail().trim());

            // 每次操作都要检查（帐号）是否重复
            AnalysisManageDTO obj = manageService.getByAdminName(objDTO.getAdminName().trim());
            if (obj != null && !Objects.equals(obj.getId(), objDTO.getId())) {
                map = OperateCode.CompositionResult(map, -10, "此帐号已存在，请重新输入！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            // 每次操作都要检查（手机号）是否重复
            // 双中横线不判断
            if (!objDTO.getMobile().equals("--")) {
                obj = manageService.getByMobile(objDTO.getMobile().trim());
                if (obj != null && !Objects.equals(obj.getId(), objDTO.getId())) {
                    map = OperateCode.CompositionResult(map, -10, "此手机号已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            // 角色中间变量
            String[] manageRoles = objDTO.getManagerole();

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                // 新增
                // 在此赋值初始值

                objDTO.setRegTime(new Date());
                objDTO.setRegIp(IpUtils.getClientIp(request));
                objDTO.setUpdateTime(new Date());
                objDTO.setMemLevel(0);
                objDTO.setIsGroup(1);   //管理帐号，此字段为1
                objDTO.setSort(0);
                objDTO.setLastLoginTime(new Date());
                objDTO.setLastLoginIp(IpUtils.getClientIp(request));
                objDTO.setLoginTimes(0);
                objDTO.setCreatePeople(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);
                objDTO.setDepId(0);   //部门

                //初始化时如果没有设置空码，则给一个默认值
                if (StringUtils.isBlank(objDTO.getPwd())) {
                    objDTO.setPwd("3DBF15878A732084");  //我也不知道是什么密码，但肯定登录不了！
                }
                objDTO.setIsBindWxapp(0);

                objDTO = manageService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    // 操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //region 管理员添加成功以后需要在[企业-管理员关联表]中增加一条记录
                IotEnterpriseManageDTO dto = new IotEnterpriseManageDTO();
                dto.setIsMain(0);
                dto.setEntId(objDTO.getEntId());
                dto.setManageId(objDTO.getId());
                dto.setAdminName(objDTO.getAdminName());
                dto.setAdminId(curr_obj.getId());
                dto.setCreateTime(new Date());
                dto.setStopFlag(0);
                dto.setDeleteFlag(0);
                enterpriseRelService.insert(dto);
                //endregion

            } else {
                // 修改
                // 在此剔除不需要修改的字段
                objDTO.setAdminName(null);

                //编辑时如果没有设置空码，则设为null
                if (StringUtils.isBlank(objDTO.getPwd())) {
                    objDTO.setPwd(null);
                }

                Boolean isNext = manageService.updateInfoById(objDTO);
                if (!isNext) {
                    // 操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

                //region 管理员添加成功以后，判断[企业-管理员关联表]中是否存在记录，不存在则新增
                AnalysisManageDTO manage = manageService.getById(objDTO.getId());

                IotEnterpriseManageDTOQuery existQuery = new IotEnterpriseManageDTOQuery();
                existQuery.setManageId(manage.getId());
                existQuery.setEntId(manage.getEntId());
                IotEnterpriseManageDTO exist = enterpriseRelService.getByQuery(existQuery);
                if (exist == null) {
                    IotEnterpriseManageDTO dto = new IotEnterpriseManageDTO();
                    dto.setIsMain(0);
                    dto.setEntId(manage.getEntId());
                    dto.setManageId(manage.getId());
                    dto.setAdminName(manage.getAdminName());
                    dto.setAdminId(curr_obj.getId());
                    dto.setCreateTime(new Date());
                    dto.setStopFlag(0);
                    dto.setDeleteFlag(0);
                    enterpriseRelService.insert(dto);
                }
                //endregion
            }

            // 每增加一名管理员都要向会员表中增加一名会员
            userService.saveAUser(UserTypeEnum.MANAGE.getKey(), objDTO.getId(), objDTO.getMobile(), objDTO.getNickName(), curr_obj.getId(), -1);

            // 删除旧权限
            rightRoleAdminRelService.delete(objDTO.getId().toString());

            // 保存新权限
            rightRoleAdminRelService.insrtForBatch(objDTO.getId(), roleids);

            // 更新用户-权限-菜单 缓存
            manageService.updateManagerRoleMenuCache(objDTO.getId());

            //region // 保存角色关系
            if (manageRoles != null && manageRoles.length > 0) {
                //这里使用简单粗暴的方法，删除后重新插入
                //1.全部删除
                TransportManageRoleRelDTOQuery roleRelQuery = new TransportManageRoleRelDTOQuery();
                roleRelQuery.setW_tableId(13);
                roleRelQuery.setW_recordId(objDTO.getId());
                roleRelQuery.setDeleteFlag(1);
                roleManageService.updateInfoByQuery(roleRelQuery);

                //2.重新插入
                for (String roleid : manageRoles) {
                    TransportManageRoleRelDTO insert = new TransportManageRoleRelDTO();
                    insert.setTableId(13);
                    insert.setRecordId(objDTO.getId());
                    insert.setRoleId(Integer.parseInt(roleid));
                    insert.setDeleteFlag(0);
                    roleManageService.insert(insert);
                }
            }
            //endregion

            //region // 保存部门关系
            String[] f_depid = request.getParameterValues("f_depid");
            String[] f_dutyid = request.getParameterValues("f_dutyid");

            if (f_depid != null && f_depid.length > 0) {
                //这里使用简单粗暴的方法，删除后重新插入
                //1.全部删除
                TransportManageDepRelDTOQuery depRelQuery = new TransportManageDepRelDTOQuery();
                depRelQuery.setW_tableId(13);
                depRelQuery.setW_recordId(objDTO.getId());
                depRelQuery.setDeleteFlag(1);
                depManageService.updateInfoByQuery(depRelQuery);

                //2.重新插入
                int i = 0;
                for (String depid : f_depid) {
                    TransportManageDepRelDTO insert = new TransportManageDepRelDTO();
                    insert.setTableId(13);
                    insert.setRecordId(objDTO.getId());
                    insert.setDepId(Integer.parseInt(depid));
                    insert.setDutyId(Integer.parseInt(f_dutyid[i]));
                    insert.setDeleteFlag(0);
                    depManageService.insert(insert);

                    i++;
                }
            }
            //endregion

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 13, objDTO.getId(), 2,
                    "更新管理员信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            // 操作成功 结果返回
            map.put("id", objDTO.getId().toString());
            map.put("parentId", "0");
            map = OperateCode.CompositionResult(map, 1);

            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            // 清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 个人信息
    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public String profile(HttpServletRequest request, Model model) {
        // 当前用户
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        model.addAttribute("currObj", curr_obj);
        model.addAttribute("headNumer", curr_obj.getHeadPicNumber());

        //获取角色权限
        List<String> roleNames = manageService.getAdminRoles(curr_obj.getId());
        model.addAttribute("roleNames", roleNames);

        return "basic/manage/profile";
    }

    @RequestMapping(value = "/profileSave", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> profileSave(HttpServletRequest request, Integer id, String remark, String duty) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        AnalysisManageDTO update = new AnalysisManageDTO();
        update.setId(id);
        update.setRemark(remark);
        update.setAdminDuty(duty);
        Boolean isNext = manageService.updateInfoById(update);

        if (isNext) {
            map.put("returnCode", 1);
            map.put("returnMessage", "个人信息更新成功！");
        } else {
            map.put("returnMessage", "个人信息更新失败！");
        }

        return map;
    }
    //endregion

    //region 删除

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            AnalysisManageDTO edit_obj = manageService.getFromCacheId(id);

            //创始者的权限只能由创始者本人修改
            if (edit_obj.getAdminName().equals("wangjunfu") && !curr_obj.getAdminName().equals("wangjunfu")) {
                map = OperateCode.CompositionResult(map, -10, "对不起，您没有权限修改此用户信息！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            Boolean isNext = manageService.delete(id);
            if (isNext) {
                //删除权限
                rightRoleAdminRelService.delete(id + "");
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 13, id, 4,
                    "删除管理员信息",
                    "管理员删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 启用禁用
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {
        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            AnalysisManageDTO edit_obj = manageService.getFromCacheId(id);

            //创始者的权限只能由创始者本人修改
            if (edit_obj.getAdminName().equals("wangjunfu") && !curr_obj.getAdminName().equals("wangjunfu")) {
                map = OperateCode.CompositionResult(map, -10, "对不起，您没有权限修改此用户信息！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            Boolean isNext = manageService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 13, id, 4,
                    "启停用管理员信息",
                    "管理员启停用：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 相似异步获取数据
    @RequestMapping(value = "/getListForLike", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getListForLike(HttpServletRequest request, String username) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder html = new StringBuilder();

        AnalysisManageDTOQuery query = new AnalysisManageDTOQuery();
        if (StringUtils.isNotBlank(username)) {
            query.setLikeName(username.trim());
        }
        query.setPageSize(20);
        query.setOrderBy("order by sort desc, id asc");
        Page<AnalysisManageDTO> dataPage = manageService.getForPage(query);

        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (AnalysisManageDTO item : dataPage.getItems()) {
                html.append("<option>").append(item.getAdminName()).append("（").append(item.getNickName()).append("）</option>");
            }
        }

        map.put("html", html);
        return map;
    }
    //endregion

    //region 根据 nickname 获取对象
    @RequestMapping(value = "/getByNicknmae", method = RequestMethod.POST)
    @ResponseBody
    public String getByNicknmae(String nickname) {
        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        map.put("nickname", "none");
        map.put("id", "0");

        try {

            if (StringUtils.isNotBlank(nickname)) {
                AnalysisManageDTO dto = manageService.getByNickName(nickname);
                if (dto != null) {
                    map.put("id", dto.getId().toString());
                    map.put("nickname", URLEncoder.encode(dto.getNickName(), "UTF-8"));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        map = OperateCode.CompositionResult(map, 1);
        result = JSONUtils.toJSON(map);
        return result;
    }
    //endregion

}